package io.knifer.gokexceltask.controller;

import io.knifer.gokexceltask.exception.InvalidParamException;
import io.knifer.gokexceltask.pojo.domain.ResultInfo;
import io.knifer.gokexceltask.service.StudentService;
import io.knifer.gokexceltask.utils.FileUtils;
import io.knifer.gokexceltask.utils.RIUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.UUID;

@RestController
@Slf4j
@RequestMapping("/api")
public class ExcelController {
    private final StudentService studentService;

    public ExcelController(StudentService studentService){
        this.studentService = studentService;
    }

    @GetMapping("/get-template")
    public void getTemplate(HttpServletResponse response) throws IOException {
        File file = ResourceUtils.getFile("classpath:template/template.xlsx");

        RIUtils.sendFile(file, response);
    }

    @PostMapping("/update-data")
    public ResultInfo<Map<String, String>> updateData(
            @RequestParam("file") MultipartFile file,
            @RequestParam("miscDataAutoInsert") boolean miscDataAutoInsert
    ) {
        if (file == null || file.isEmpty()){
            throw new InvalidParamException();
        }

        Map<String, String> errorMsg = null;

        try {
            errorMsg = studentService.saveByExcel(file, miscDataAutoInsert);
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }

        return RIUtils.create(200, null, errorMsg);
    }

    @GetMapping("/export-data")
    public void exportData(HttpServletResponse response) throws IOException {
        UUID fileName = studentService.exportStudentDataAsExcel();
        File file = FileUtils.getResourceFile("temp" + File.separator + fileName + ".xlsx");

        if (file.length() > 0){
            RIUtils.sendFile(file, "导出学生数据.xlsx", response);
            file.delete();
        }else{
            RIUtils.send("哦吼，发生了未知错误，请稍后重试", response);
        }
    }

    @GetMapping("/export-mock-data")
    public void exportMockData(@RequestParam(value = "rows", required = false) Integer rows, HttpServletResponse response) throws IOException {
        UUID fileName = studentService.exportAndMockStudentDataAsExcel(rows != null && rows > 0 ? rows : 5000);
        File file = FileUtils.getResourceFile("temp" + File.separator + fileName + ".xlsx");

        if (file.length() > 0){
            RIUtils.sendFile(file, "模拟学生数据.xlsx", response);
            file.delete();
        }else{
            RIUtils.send("哦吼，发生了未知错误，请稍后重试", response);
        }
    }
}
